import store from '@/store'
import md5 from 'js-md5'


var websock = null
var globalCallback = null
const WS_HOST = process.env.VUE_APP_WS_HOST

//心跳检测
var heartCheck = {
  timeoutBeat: 10000,
  timeout: 30000,
  timeoutObj: null,
  serverTimeoutObj: null,
  startBeat: function() {
    setInterval(()=>{websock.send("nop"); }, 30000)
  },
  start: function(){
    console.log(" WSocket 心跳检测");
    var self = this;
    this.timeoutObj && clearTimeout(this.timeoutObj);
    this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
    this.timeoutObj = setTimeout(function(){
      //这里发送一个心跳，后端收到后，返回一个心跳消息，
      //onmessage拿到返回的心跳就说明连接正常
      console.log(' WSocket 连接重试');
      self.serverTimeoutObj = setTimeout(function() {
        console.log(' WSocket close');
        websock.close();
      }, self.timeout);
    }, this.timeout)
  }
}

// 初始化weosocket
function initWebSocket(userid) {
  if (userid == null) {
    userid = sessionStorage.getItem('w_username')
  }
  const time = new Date();
  let year = time.getFullYear()
  let month = time.getMonth() + 1
  let day = time.getDate()
  let s = year
  if (month < 10) {
    s += '0'
  }
  s += month
  s += '-'
  if (day < 10) {
    s += '0'
  }
  s = s + day + 'WEB_' + userid
  var ws = 'ws://' + WS_HOST + '/wsapi/WEB_' + userid + '/' + md5(s)
  websock = new WebSocket(ws)
  websock.onmessage = function (e) {
    websocketonmessage(e)
  }
  websock.onclose = function (e) {
    websocketclose(e)
  }
  websock.onopen = function () {
    websocketOpen()
    heartCheck.startBeat();
  }

  // 连接发生错误的回调方法
  websock.onerror = function () {
    console.log('WebSocket连接发生错误')
  }
}

// 实际调用的方法
function sendSock(agentData, callback) {
  globalCallback = callback
  if (websock.readyState === websock.OPEN) {
    // 若是ws开启状态
    websocketsend(agentData)
  } else if (websock.readyState === websock.CONNECTING) {
    // 若是 正在开启状态，则等待1s后重新调用
    setTimeout(function () {
      sendSock(agentData, callback)
    }, 1000)
  } else {
    // 若未开启 ，则等待1s后重新调用
    setTimeout(function () {
      sendSock(agentData, callback)
    }, 1000)
  }
}

// 数据接收
function websocketonmessage(e) {
  if (e == null || 'nop' === e.data) {
    return
  }
  let obj = JSON.parse(e.data)
  // console.log(e)
  if (obj.code == null) {
    return
  }

  if (obj.code == 10) {
    console.log('dispatch deviceChanged')
    store.dispatch('device/deviceChange', JSON.stringify(obj.data))
  } else if (obj.code == 8) {
    console.log('video finished')
    store.dispatch('device/videoFinish', JSON.stringify(obj.data))
  } else if (obj.code <= 14) { // 6 11 12 13 14 app相关指令
    console.log('dispatch deviceAppChange')
    store.dispatch('device/deviceAppChange', JSON.stringify(obj.data))
  }
}

// 数据发送
function websocketsend(agentData) {
  websock.send(JSON.stringify(agentData))
}

// 关闭
function websocketclose(e) {
  console.log('连接close')
  store.dispatch('app/wsocketChange', '0')
}

// 创建 websocket 连接
function websocketOpen(e) {
  console.log('连接Open')
  store.dispatch('app/wsocketChange', '1')
}

// 将方法暴露出去
export {
  sendSock, initWebSocket
}
